package settings

import (
	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
)

type SystemConfig struct {
	*AppConfig   `mapstructure:"app"`
	*LogConfig   `mapstructure:"log"`
	*DbConfig    `mapstructure:"mysql"`
	*RedisConfig `mapstructure:"redis"`
}

type AppConfig struct {
	Name      string `mapstructure:"name"`
	Mode      string `mapstructure:"mode"`
	Version   string `mapstructure:"version"`
	Port      int    `mapstructure:"port"`
	StartTime string `mapstructure:"start_time"`
	MchId     int64  `mapstructure:"mch_id"`
}

type LogConfig struct {
	Level      string `mapstructure:"level"`
	Filename   string `mapstructure:"filename"`
	MaxSize    int    `mapstructure:"max_size"`
	MaxAge     int    `mapstructure:"max_age"`
	MaxBackups int    `mapstructure:"max_backups"`
	Compress   bool   `mapstructure:"compress"`
}

type DbConfig struct {
	Host         string `structure:"host"`
	Port         string `structure:"port"`
	User         string `structure:"user"`
	Password     string `structure:"password"`
	DbName       string `structure:"dbname"`
	MaxOpenConns int    `structure:"max_open_conns"`
	MaxIdleConns int    `structure:"max_idle_conns"`
}

type RedisConfig struct {
	Addr     string `mapsturcture:"addr"`
	Port     string `mapsturcture:"port"`
	Password string `mapsturcture:"password"`
	Db       int    `mapsturcture:"db"`
	PoolSize int    `mapsturcture:"pool_size"`
}

var Config = new(SystemConfig)

func Init() (err error) {
	viper.SetConfigFile("config.yaml")
	err = viper.ReadInConfig()
	if err != nil {
		return
	}
	err = viper.Unmarshal(Config)
	if err != nil {
		return err
	}
	viper.WatchConfig()
	viper.OnConfigChange(func(in fsnotify.Event) {
		_ = viper.Unmarshal(Config)
	})
	return
}
